//封装
import axios from 'axios'
import nprogress from 'nprogress'
import 'nprogress/nprogress.css'
import store from '@/store'
//用create方法创建一个axios实例
const url=process.env.NODE_ENV==='development' ? '/api' : 'http://gmall-h5-api.atguigu.cn/'
const http=axios.create({
    //配置对象
    baseURL:url,
    timeout:50000
})

//请求拦截
http.interceptors.request.use((config)=>{
    if (store.state.detail.uuid_token && !store.state.user.token) {
        // userTempId和后台约定好的字段
        config.headers.userTempId = store.state.detail.uuid_token 
    }
    if (store.state.user.token) {
        config.headers.token = store.state.user.token
    }
    //拦截请求加入滚动条
   nprogress.start()
   return config
})

//响应拦截器
http.interceptors.response.use((res)=>{
    //成功的回调函数
    //拦截响应加入滚动条
    nprogress.done()
    return res.data
},(error)=>{
    nprogress.done()
    //响应失败的回调函数
    return error.config
})

export default http